package com.android.equipment.ui

import android.os.Bundle
import android.zyapi.CommonApi
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.android.equipment.R
import com.android.equipment.adapter.MainPagerAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.dao.DeviceModel
import com.android.equipment.dao.operate.DaoConfigModel
import com.android.equipment.dao.operate.DaoDeviceModel
import com.android.equipment.dao.operate.DaoDeviceModelAlamConfig
import com.android.equipment.databinding.ActivityMainBinding
import com.android.equipment.ui.fragment.HomeFragment
import com.android.equipment.ui.fragment.UserFragment
import com.android.equipment.utils.DataTreatUtil
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.utils.DateUtils
import java.io.UnsupportedEncodingException


class MainActivity : BaseActivity<ActivityMainBinding>() {

    private var isFirstOpen = false

    private var fragments: MutableList<Fragment> = ArrayList()
    private var sb: StringBuffer = StringBuffer()
//
//    //已打开的设备列表
//    private var devices: MutableSet<UsbDevice> = Collections.synchronizedSet(HashSet<UsbDevice>())
//
//
//    //保存各个串口的接收计数
//    private var readCountMap: HashMap<String, Int> = HashMap()

    private val mCommonApi: CommonApi by lazy { CommonApi() }
    private var heightCom: Int = 0
    private var loraCom: Int = 0


    override fun setLayoutContent(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    @Throws(Exception::class)
    override fun initView(savedInstanceState: Bundle?) {
        val adapter = MainPagerAdapter(this, initFragment())
        binding.vp.adapter = adapter
        binding.bnv.itemIconTintList = null
        binding.vp.offscreenPageLimit = 2
    }


    override fun initData() {
        //添加默认的型号  智能安全带
        val deviceModeList = DaoDeviceModel.getInstance().getNotDelDeviceModel()
        if (deviceModeList.isNullOrEmpty()) {
            val deviceModel = DeviceModel()
            deviceModel.deviceModel = "智能安全带"
            deviceModel.modelCode = "DL-AD9918A"
            deviceModel.prefix = "AD99"
            deviceModel.protocol = 2
            deviceModel.createTime = DateUtils.getYearDataFormat(System.currentTimeMillis())
            deviceModel.handler = "HCHandler"
            val deviceModelId = DaoDeviceModel.getInstance().addDeviceModel(deviceModel)
            //添加默认节点配置
            DaoConfigModel.getInstance().addDefaultConfigModel(deviceModelId)

            //添加默认报警配置
            DaoDeviceModelAlamConfig.getInstance()
                .addDefaultDeviceModelAlamConfig(deviceModel.modelCode)

        }


//        if (!usbFeatureSupported()) {
//            ToastUtil.showToast(this, "系统不支持USB Host功能")
//            exitProcess(0)
//        }
//        monitorUSBState()


//        requestPermission()

//        val data = "AT+MDAT=34,443030303031,44303030303101204A646464FF642300000000000000000076832967007B8640A09E,-24"
//        parse(data)

        //供电模板供电
        setGpio()
        //设置串口
        setCom()
    }


    private fun setGpio() {
        mCommonApi.setGpioDir(27, 1)
        val ret27 = mCommonApi.setGpioOut(27, 1)

        mCommonApi.setGpioDir(25, 1)
        val ret25 = mCommonApi.setGpioOut(25, 1)

        mCommonApi.setGpioDir(23, 1)
        val ret23 = mCommonApi.setGpioOut(23, 1)
    }

    private fun setCom() {
        heightCom = mCommonApi.openCom("/dev/ttyS0", 115200, 8, 'N', 1) //接收大气压高度串口数据
        if (heightCom > 0) {
            isFirstOpen = true
            readHeightData(heightCom)
        }
        loraCom = mCommonApi.openCom("/dev/ttyS1", 460800, 8, 'N', 1) //接收Lora串口数据
        if (loraCom > 0) {
            ToastUtils.showShort("打开Lora数据串口成功")
            readLoraData(loraCom)
            handler()
        }
    }

    private fun readHeightData(heightCom: Int) {
        Thread {
            while (true) {
                val ret: Int
                val buf = ByteArray(512 + 1)
                ret = mCommonApi.readComEx(heightCom, buf, 512, 0, 0)
                if (ret <= 0) {
                    try {
                        Thread.sleep(1000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    continue
                }
                val receive = ByteArray(ret)
                System.arraycopy(buf, 0, receive, 0, ret)
                try {
                    val str = java.lang.String(receive, "gb2312")
                    if (!StringUtils.isEmpty(str)) {
                        if (str.contains("Height")) {
                            val lines = str.split("\r\n")
                            val lastLine = lines.last()
                            // 使用正则表达式提取 Height 值
                            val regex = "Height\\s*=\\s*(\\d+\\.\\d+)".toRegex()
                            val matchResult = regex.find(lastLine)
                            if (matchResult != null) {
                                val height = matchResult.groupValues[1]
                                if (isFirstOpen){
                                    isFirstOpen = false
                                    SPUtils.getInstance().put("startHeight", height)
                                }
                                SPUtils.getInstance().put("height", height)
                            }
                        }
                    }

                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
            }

        }.start()
    }

    private fun readLoraData(loraCom: Int) {
        Thread {
            while (true) {
                val ret: Int
                val buf = ByteArray(512 + 1)
                ret = mCommonApi.readComEx(loraCom, buf, 512, 0, 0)
                if (ret <= 0) {
                    try {
                        Thread.sleep(1000)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    continue
                }
                val receive = ByteArray(ret)
                System.arraycopy(buf, 0, receive, 0, ret)
                var str = ""
                try {
                    str = java.lang.String(receive, "gb2312").toString()
                    LogUtils.e("loraComReceiveData: $str")
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
                if (!StringUtils.isEmpty(str)) {
                    sb.append(str)
//                    if (str.startsWith("AT+MDAT=")) {
//                        if (strBuilder.toString().isNotEmpty()) {
//                            strBuilder.clear()
//                        }
//                        strBuilder.append(str)
//                    } else {
//                        if (!StringUtils.isEmpty(strBuilder.toString())) {
//                            strBuilder.append(str)
//                        }
//
//                        val commaCount = strBuilder.toString().count { it == ',' }
//                        if (commaCount > 4) {
//                            val data = strBuilder.toString()
//                            strBuilder.clear()
//                            LogUtils.d("loraComReceive: $data")
//                            runOnUiThread {
//                               // DataTreatUtil.parse(data)
//                            }
//                        }
//                    }


                }
            }

        }.start()
    }

    private fun handler() {
        val thread = Thread {
            while (true) {
                try {
                    Thread.sleep(1000)
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }

                val i2: Int = sb.toString().indexOf("AT+MDAT=")
                if (i2 == -1) {
                    continue
                }

                val split = sb.toString().split("AT+MDAT=")
                if (split.isEmpty()) {
                    continue
                }

                val split1 = split[1].split(",").toMutableList()

                if (split1.size >= 6) {
                    //可以进行处理
                    var j = 4
                    if (split1[5].contains("\r")) {
                        j = split1[5].indexOf("\r")
                    } else if (!split1[5].contains("\r") && split1[5].contains("\n")) {
                        j = split1[5].indexOf("\n")
                    }


                    split1[5] = split1[5].substring(0, j)

                    var l = 8 + 5
                    for (i in 0..5) {
                        l += split1[i].length
                    }

                    try {
                        val data: String = sb.substring(i2, i2 + l)
                        runOnUiThread {
                            DataTreatUtil.parse(data)
                        }
                    } catch (ee: Exception) {

                    }

                    val substring = sb.substring(i2 + l)
                    sb = StringBuffer()
                    sb.append(substring)
                }
            }
        }
        thread.start()
    }


    override fun initEvent() {
        super.initEvent()
        binding.bnv.setOnItemSelectedListener { item ->
            val itemId = item.itemId
            when (itemId) {
                R.id.item_home -> binding.vp.currentItem = 0
                R.id.item_user -> binding.vp.currentItem = 1
            }
            true
        }

        binding.vp.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                when (position) {
                    0 -> binding.bnv.selectedItemId = R.id.item_home
                    1 -> binding.bnv.selectedItemId = R.id.item_user
                }
            }
        })
    }

    private fun initFragment(): List<Fragment> {
        fragments.add(HomeFragment())
        fragments.add(UserFragment())
        return fragments
    }

    override fun onDestroy() {
        super.onDestroy()
        if (heightCom > 0) {
            mCommonApi.closeCom(heightCom)
        }

        if (loraCom > 0) {
            mCommonApi.closeCom(loraCom)
        }
    }

//    private fun usbFeatureSupported(): Boolean {
//        val bool = this.packageManager.hasSystemFeature(
//            "android.hardware.usb.host"
//        )
//        return bool
//    }

//    private fun monitorUSBState() {
//        WCHUARTManager.getInstance().setUsbStateListener(object : IUsbStateChange {
//            override fun usbDeviceDetach(device: UsbDevice) {
//                //设备移除
//                removeReadDataDevice(device)
//            }
//
//            override fun usbDeviceAttach(device: UsbDevice) {
//                //设备插入
//            }
//
//            override fun usbDevicePermission(device: UsbDevice, result: Boolean) {
//                //请求打开设备权限结果
//            }
//        })
//    }

//    private fun removeReadDataDevice(usbDevice: UsbDevice) {
//        synchronized(devices) {
//            devices.remove(usbDevice)
//        }
//    }

//    private fun requestPermission() {
//        XXPermissions.with(mContext!!)
//            .permission(Permission.WRITE_EXTERNAL_STORAGE)
//            .request(object : OnPermissionCallback {
//                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
//                    if (!allGranted) {
//                        //部分获取成功
//                        XXPermissions.startPermissionActivity(mContext!!, permissions)
//                        return
//                    }
//
//                    openUsbDevice()
//
//                }
//
//                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
//                    if (doNotAskAgain) {
//                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                        XXPermissions.startPermissionActivity(mContext!!, permissions)
//                    } else {
//                        ToastUtils.showShort("获取权限失败！")
//                    }
//                }
//            })
//    }


//    private fun openUsbDevice() {
//
//        //枚举符合要求的设备
//        val usbDeviceArrayList = WCHUARTManager.getInstance().enumDevice()
//        if (usbDeviceArrayList.size == 0) {
//            ToastUtils.showShort("no matched devices")
//            return
//        }
//        val usbDevice = usbDeviceArrayList[0]
//        if (WCHUARTManager.getInstance().isConnected(usbDevice)) {
//            ToastUtils.showShort("当前设备已经打开")
//            return
//        }
//        try {
//            val b = WCHUARTManager.getInstance().openDevice(usbDevice)
//            if (b) {
//                //打开成功
//                if (!setSerialParameter(usbDevice)) {
//                    ToastUtils.showShort("参数设置失败")
//                }
//                //初始化接收计数
//                var serialCount = 0
//                try {
//                    serialCount = WCHUARTManager.getInstance().getSerialCount(usbDevice)
//                } catch (e: java.lang.Exception) {
//                    e.printStackTrace()
//                }
//                for (i in 0 until serialCount) {
//                    readCountMap.put(getSerialKey(usbDevice, i), 0)
//                }
//                //将该设备添加至已打开设备列表,在读线程ReadThread中,将会读取该设备的每个串口数据
//                addToReadDeviceSet(usbDevice)
//
//                //registerModemStatusCallback(usbDevice)
//                registerDataCallback(usbDevice)
//            } else {
//                ToastUtils.showShort("打开失败")
//            }
//        } catch (e: ChipException) {
//            LogUtils.d(e.message)
//        } catch (e: NoPermissionException) {
//            //没有权限打开该设备
//            //申请权限
//            ToastUtils.showShort("没有权限打开该设备")
//            requestPermission(usbDevice)
//        } catch (e: UartLibException) {
//            e.printStackTrace()
//        }
//    }


//    //设置串口参数
//    private fun setSerialParameter(usbDevice: UsbDevice?, ): Boolean {
//        try {
//            val b = WCHUARTManager.getInstance().setSerialParameter(
//                usbDevice!!,
//                0,
//                460800,
//                8,
//                1,
//                0,
//                false
//            )
//            return b
//        } catch (e: java.lang.Exception) {
//            LogUtils.d(e.message)
//        }
//        return false
//    }


    /**
     * 申请读写权限
     * @param usbDevice
     */
//    private fun requestPermission(usbDevice: UsbDevice) {
//        try {
//            WCHUARTManager.getInstance().requestPermission(this, usbDevice)
//        } catch (e: java.lang.Exception) {
//            LogUtils.d(e.message)
//        }
//    }


//    private fun getSerialKey(device: UsbDevice, serialNumber: Int): String {
//        return String.format(Locale.getDefault(), "%s_%d", device.deviceName, serialNumber)
//    }

//    private fun addToReadDeviceSet(usbDevice: UsbDevice) {
//        synchronized(devices) {
//            devices.add(usbDevice)
//        }
//    }


//    private fun registerDataCallback(usbDevice: UsbDevice) {
//        try {
//            WCHUARTManager.getInstance().registerDataCallback(
//                usbDevice
//            ) { serialNumber, buffer, length -> //LogUtil.d(String.format(Locale.getDefault(),"serial %d receive data %d:%s", serialNumber,length, FormatUtil.bytesToHexString(buffer, length)));
//                //1.注意回调的执行线程与调用回调方法的线程属于同一线程
//                //2.此处所在的线程将是线程池中多个端点的读取线程，可打印线程id查看
//                //3.buffer是底层数组，如果此处将其传给其他线程使用，例如通过runOnUiThread显示数据在界面上,
//                //涉及到线程切换需要一定时间，buffer可能被读到的新数据覆盖，可以新建一个临时数组保存数据
//
//                val data = ByteArray(length)
//                //                    String s1 = new String(buffer, StandardCharsets.UTF_8);
//                //                    String s = BinaryParseUtil.bytesToHexFun3(buffer);
//                //LogUtil.d("当前转换后的S====>"+s);
//                System.arraycopy(buffer, 0, data, 0, data.size)
//                updateReadData(usbDevice, serialNumber, data, length)
//            }
//        } catch (e: java.lang.Exception) {
//            LogUtils.d(e.message)
//        }
//    }


//    private fun updateReadData(usbDevice: UsbDevice, serialNumber: Int, buffer: ByteArray?, length: Int) {
//        if (buffer == null) {
//            return
//        }
//        runOnUiThread(Runnable {
//            var integer = readCountMap[getSerialKey(usbDevice, serialNumber)]
//                ?: //不包含此key
//                return@Runnable
//            //更新计数
//            integer += length
//            readCountMap[getSerialKey(usbDevice, serialNumber)] = integer
//
//            //
//            var result = ""
//
//            //                byte[] bytes = BinaryParseUtil.hexStringToByteArray(s);
//            val payload = String(buffer, StandardCharsets.UTF_8)
//            LogUtils.d("当前转换后的S1111111111111====>$payload")
//
//            if (payload.startsWith("High")) {
//                SPUtils.getInstance().put("height", payload)
//            } else {
//                if (payload.startsWith("AT+MDAT=")) {
//                    if (strBuilder.toString().isNotEmpty()) {
//                        strBuilder.clear()
//                    }
//                    strBuilder.append(payload)
//                } else {
//                    if (!StringUtils.isEmpty(strBuilder.toString())) {
//                        strBuilder.append(payload)
//                    }
//
//                    val commaCount = strBuilder.toString().count { it == ',' }
//                    if (commaCount >= 3) {
//                        val data = strBuilder.toString()
//                        strBuilder.clear()
//                        DataTreatUtil.parse(data)
//                    }
//                }
//            }
//        })
//    }

    override fun setStatusBar() {
        //super.setStatusBar()
    }
}